﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WoSoft.PACS.Data.CheckData;
using System.Runtime.InteropServices;
using System.Reflection;
using System.IO;

namespace WoSoft.PACS.Win.Forms.SubForms
{
    public partial class FrmDicomView : WoSoft.PACS.Win.FrmBase
    {
        Bitmap myBmp = null;
        Point mouseDownPoint = new Point(); //记录拖拽过程鼠标位置
        bool isMove = false;    //判断鼠标在picturebox上移动时，是否处于拖拽过程(鼠标左键是否按下)
        int zoomStep = 20;      //缩放步长

        bool showTag = false;//tag/ 影像切换
        DicomHandler handler;

        //检查的业务对象
        private CheckApp _checkapp = new CheckApp();

        //当前选择病人的申请ID
        private string appFormID = string.Empty;

        public FrmDicomView(string appID)
        {
            InitializeComponent();
            appFormID = appID;
            UIswitch();
        }

        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage(
        int hWnd,  //  handle  to  destination  window  
        int Msg,  //  message  
        int wParam,  //  first  message  parameter  
        ref  COPYDATASTRUCT lParam  //  second  message  parameter  
        );

        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        private static extern int FindWindow(string lpClassName, string lpWindowName);

        public delegate bool EnumWindowProc(int hWnd, int parameter);

        [DllImport("user32.dll", EntryPoint = "EnumChildWindows")]
        public static extern bool EnumChildWindows(int window, EnumWindowProc callback, int lParam);

        [DllImport("User32.dll", EntryPoint = "FindWindowEx")]
        private static extern int FindWindowEx(int hwndParent, int hwndChildAfter, string lpszClass, string lpszWindow);

        public struct COPYDATASTRUCT
        {
            public IntPtr dwData;
            public int cbData;
            [MarshalAs(UnmanagedType.LPStr)]
            public string lpData;
        }

        const int WM_COPYDATA = 0x004A;

        private void SendMessageToMain(string strMSG)//发送消息到Main平台    
        {
            int maindHwnd = FindWindow(null, "检查报告");//获得主窗体的句柄 
            if (maindHwnd != 0)
            {
                byte[] sarr = System.Text.Encoding.Default.GetBytes(strMSG);
                int len = sarr.Length;

                COPYDATASTRUCT cds;
                cds.dwData = (IntPtr)100;
                cds.lpData = strMSG;
                cds.cbData = len + 1;
                SendMessage(maindHwnd, WM_COPYDATA, 0, ref  cds);
            }
        }

        void UIswitch()
        {
            if (handler != null)
            {
                windowWidthTxt.Text = handler.windowWith.ToString();
                windowCenterTxt.Text = handler.windowCenter.ToString();
            }
            if (showTag)
            {
                textBox1.Visible = true;
                panel.Visible = false;
                toolStripButton2.Text = "切换到影像";
            }
            else
            {
                textBox1.Visible = false;
                panel.Visible = true;

                toolStripButton2.Text = "切换到tag";
            }
            if (backgroundWorker.IsBusy)
            {
                Bitmap loadImg = new Bitmap(200, 100);
                Graphics g = Graphics.FromImage(loadImg);
                g.DrawString("载入中，请稍后...", new Font(new FontFamily("Arial"), 15.0f), Brushes.Black, new PointF(0, 0));
                pictureBox.Image = loadImg;
                pictureBox.SizeMode = PictureBoxSizeMode.CenterImage;
            }
        }

        private void toolStripLabel1_Click(object sender, EventArgs e)
        {
            if (backgroundWorker.IsBusy)
            {
                MessageBox.Show("影像载入中，请稍后...");
                return;
            }

            if (openFileDialog.ShowDialog() != DialogResult.OK)
                return;

            string fileName = openFileDialog.FileName;
            handler = new DicomHandler(fileName);
            handler.readAndShow(textBox1);
            pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
            this.Text = "DicomViewer-" + openFileDialog.FileName;
            backgroundWorker.RunWorkerAsync();
            //UIswitch();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (object.Equals(myBmp, null)) return;

            if (backgroundWorker.IsBusy)
            {
                MessageBox.Show("影像载入中，请稍后...");
                return;
            }
            string fileName = Guid.NewGuid().ToString();
            var captureImgsPath = Path.Combine(Application.StartupPath, "CaptureImages");
            var currentDay = DateTime.Now.ToString("yyyyMMdd");
            if (!Directory.Exists(captureImgsPath))
            {//路径不存在,创建根目录
                Directory.CreateDirectory(captureImgsPath);
            }

            //检查当前的目录是否存
            var imgSavePath = Path.Combine(captureImgsPath, currentDay);
            if (!Directory.Exists(imgSavePath))
            {
                Directory.CreateDirectory(imgSavePath);
            }
            var jpgfileName = Path.Combine(imgSavePath, fileName + ".jpg");

            handler.saveAs(jpgfileName);

            var dat = ImageToByte(myBmp);

            //保存图像(到数据库)
            this._checkapp.SaveImage(fileName, this.appFormID, dat);

            //刷新主界面图像
            //SendMessageToMain("refresh");
            SendMessageToMain(fileName + "|" + jpgfileName);
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            showTag = !showTag;
            UIswitch();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            pictureBox.SizeMode = PictureBoxSizeMode.AutoSize;
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            if (backgroundWorker.IsBusy || handler == null)
            {
                MessageBox.Show("影像载入中，请稍后...");
                return;
            }

            int.TryParse(windowWidthTxt.Text, out handler.windowWith);
            int.TryParse(windowCenterTxt.Text, out handler.windowCenter);

            backgroundWorker.RunWorkerAsync();
            //UIswitch();
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            if (handler.getImg())
            {
                myBmp = handler.gdiImg;
                pictureBox.Image = myBmp;
            }
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            UIswitch();
        }

        private void pictureBox_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mouseDownPoint.X = Cursor.Position.X;
                mouseDownPoint.Y = Cursor.Position.Y;
                isMove = true;
                pictureBox.Focus();
            }
        }

        private void pictureBox_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMove = false;
            }
        }

        private void pictureBox_MouseMove(object sender, MouseEventArgs e)
        {
            pictureBox.Focus();
            if (isMove)
            {
                int x, y;
                int moveX, moveY;
                moveX = Cursor.Position.X - mouseDownPoint.X;
                moveY = Cursor.Position.Y - mouseDownPoint.Y;
                x = pictureBox.Location.X + moveX;
                y = pictureBox.Location.Y + moveY;
                pictureBox.Location = new Point(x, y);
                mouseDownPoint.X = Cursor.Position.X;
                mouseDownPoint.Y = Cursor.Position.Y;
            }
        }

        private void pictureBox_MouseWheel(object sender, MouseEventArgs e)
        {
            int x = e.Location.X;
            int y = e.Location.Y;
            int ow = pictureBox.Width;
            int oh = pictureBox.Height;
            int VX, VY;
            if (e.Delta > 0)
            {
                pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
                pictureBox.Width += zoomStep;
                pictureBox.Height += zoomStep;

                PropertyInfo pInfo = pictureBox.GetType().GetProperty("ImageRectangle", BindingFlags.Instance |
                    BindingFlags.NonPublic);
                Rectangle rect = (Rectangle)pInfo.GetValue(pictureBox, null);

                pictureBox.Width = rect.Width;
                pictureBox.Height = rect.Height;
            }
            if (e.Delta < 0)
            {
                pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
                if (pictureBox.Width < myBmp.Width / 10)
                    return;

                pictureBox.Width -= zoomStep;
                pictureBox.Height -= zoomStep;
                PropertyInfo pInfo = pictureBox.GetType().GetProperty("ImageRectangle", BindingFlags.Instance |
                    BindingFlags.NonPublic);
                Rectangle rect = (Rectangle)pInfo.GetValue(pictureBox, null);
                pictureBox.Width = rect.Width;
                pictureBox.Height = rect.Height;
            }

            VX = (int)((double)x * (ow - pictureBox.Width) / ow);
            VY = (int)((double)y * (oh - pictureBox.Height) / oh);
            pictureBox.Location = new Point(pictureBox.Location.X + VX, pictureBox.Location.Y + VY);
        }

        private void panel_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mouseDownPoint.X = Cursor.Position.X;
                mouseDownPoint.Y = Cursor.Position.Y;
                isMove = true;
            }
        }

        private void panel_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMove = false;
            }
        }

        private void panel_MouseMove(object sender, MouseEventArgs e)
        {
            panel.Focus();
            if (isMove)
            {
                int x, y;
                int moveX, moveY;
                moveX = Cursor.Position.X - mouseDownPoint.X;
                moveY = Cursor.Position.Y - mouseDownPoint.Y;
                x = pictureBox.Location.X + moveX;
                y = pictureBox.Location.Y + moveY;
                pictureBox.Location = new Point(x, y);
                mouseDownPoint.X = Cursor.Position.X;
                mouseDownPoint.Y = Cursor.Position.Y;
            }
        }

        private void FrmDicomView_Load(object sender, EventArgs e)
        {
            pictureBox.Width = panel.Width;
            pictureBox.Height = panel.Height;
            pictureBox.Location = panel.Location;
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
            pictureBox.Location = panel.Location;
            pictureBox.Width = panel.Width;
            pictureBox.Height = panel.Height;
        }

        private void contextMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            int ow = pictureBox.Width;
            int oh = pictureBox.Height;
            switch (e.ClickedItem.Name)
            {
                case "放大ToolStripMenuItem":
                    pictureBox_MouseWheel(null, new MouseEventArgs(System.Windows.Forms.MouseButtons.Middle, 1, Control.MousePosition.X, Control.MousePosition.Y, 1));
                    break;
                case "缩小ToolStripMenuItem":
                    pictureBox_MouseWheel(null, new MouseEventArgs(System.Windows.Forms.MouseButtons.Middle, 1, Control.MousePosition.X, Control.MousePosition.Y, -1));
                    break;
                case "旋转90ToolStripMenuItem":
                    myBmp.RotateFlip(RotateFlipType.Rotate90FlipNone);
                    this.pictureBox.Image = myBmp;
                    break;
                case "旋转180ToolStripMenuItem":
                    myBmp.RotateFlip(RotateFlipType.Rotate180FlipNone);
                    this.pictureBox.Image = myBmp;
                    break;           
                default:
                    break;
            }
        }

    }
}
